﻿using Admin.Core.Common.Auth;
using Admin.Core.Common.Input;
using Admin.Core.Common.Output;
using Admin.Core.Common.ParamInput;
using Admin.Core.Model.Warehouse;
using Admin.Core.Repository.Warehouse.StockIn;
using Admin.Core.Service.Warehouse.StockIn.Input;
using Admin.Core.Service.Warehouse.StockIn.Output;
using AutoMapper;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Admin.Core.Service.Warehouse.StockIn
{
    public  class StockInService: IStockInService
    {

        private readonly IUser _user;
        private readonly IMapper _mapper;
        private readonly IStockInRepository _stockInRepository;
        //private readonly IXbcMaterrialRepository _xbcMaterrialRepository;
        //private readonly IXbcWarehouseRepository _xbcWarehouseRepository;
        //private readonly IXbcLocationRepository _xbcLocationRepository;
        //private readonly IXbcTypeRepository _xbcTypeRepository;
        public StockInService(IUser user, IMapper mapper
            , IStockInRepository stockInRepository
            //, IXbcMaterrialRepository xbcMaterrialRepository
            //, IXbcTypeRepository xbcTypeRepository
            //, IXbcWarehouseRepository xbcWarehouseRepository
            //,IXbcLocationRepository xbcLocationRepository
            )
        {
            _user = user;
            _mapper = mapper;
            _stockInRepository = stockInRepository;
            //_xbcTypeRepository = xbcTypeRepository;
            //_xbcWarehouseRepository = xbcWarehouseRepository;
            //_xbcLocationRepository = xbcLocationRepository;
            //_xbcMaterrialRepository = xbcMaterrialRepository;
        }

        /// <summary>
        /// 获取物料类型
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> GetAsync(long id)
        {
            var result = await _stockInRepository.GetAsync<StockInGetOutput>(id);
            return ResponseOutput.Ok(result);
        }


        /// <summary>
        /// 分页查询仓库入库记录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> PageAsync(PageInput<StockInFilterInput> input)
        {
            var key = input.Filter?.Wllb;
            var list = await _stockInRepository.baseRepository.Select
            .WhereIf(key != null, a => a.XbcMatterrial.XbcTypeId.Equals(key))
            //.WhereIf(typeId != null, a => a.XbcTypeId.Equals(typeId))
            .Count(out var total)
            .OrderByDescending(true, c => c.Id)
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync(a => new StockInListOutput
            {
                XbcMatterrialId = a.XbcMatterrialId
            ,
                CustomerCode = a.XbcMatterrial.Khdm.Name
            ,
                KcdwId = a.XbcMatterrial.CkdwId
            ,
                Wlms = a.XbcMatterrial.Name
            ,
                Wlgg = a.XbcMatterrial.Wlgg
            ,
                Dw = a.XbcMatterrial.Ckdw.Name
            });
            //var data = new VxePageOutPut<StockInListOutput>()
            //{
            //    Result = list,
            //    Page = new VxePage { currentPage = input.CurrentPage, pageSize = input.PageSize, total = total, totalResult = total }
            //};
            var data = new PageOutput<StockInListOutput>()
            {
                List = list,
                Total = total
            };
            return ResponseOutput.Ok(data);
        }

        /// <summary>
        /// 分页查询仓库入库库存记录
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<IResponseOutput> PageKcAsync(PageInput<StockInCkFilterInput> input)
        {
            var key = input.Filter?.Wllb;
            var code = input.Filter?.WlCode;
            var list = await _stockInRepository.baseRepository.Select
            .WhereIf(key != null, a => a.XbcMatterrial.XbcTypeId.Equals(key))
            .WhereIf(code != null, a => a.XbcMatterrial.Code.Contains(code))
            .Where(a=>a.RemainNum>0)
            .Count(out var total)
            .OrderBy(true, c => c.MaterArriDate)
            //.OrderByDescending(true, c => c.Id)
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync(a => new StockInKcListOutput
            {
                StockInId= a.Id
            ,
                CustomerCode = a.XbcMatterrial.Khdm.Name
            ,
                AddStorageBatchCode = a.AddStorageBatchCode
            ,
                Dw = a.XbcMatterrial.Ckdw.Name
            ,
                Wlms = a.XbcMatterrial.Name
            ,
                Wlgg = a.XbcMatterrial.Wlgg
            ,
                WlCode = a.XbcMatterrial.Code
            ,
                XbcLocationCode = a.XbcMatterrial.XbcLocation.Name
            ,
            });
            var data = new PageOutput<StockInKcListOutput>()
            {
                List = list,
                Total = total
            };
            return ResponseOutput.Ok(data);
        }

        public async Task<IResponseOutput> AddAsync(List<StockInAddInput> input)
        {
            var list = _mapper.Map<List<StockInEntity>>(input);
            var year = DateTime.Now.Year.ToString();
            list.ForEach(async (x) => { 
                x.TenantId = _user.TenantId;
                string sql = $@"select ST_STOCKIN_CODE_SEQ.nextval  from DUAL";
                var result = await _stockInRepository.Orm.Ado.QueryAsync<SeqValue>(sql);
                var suffix =  result[0].Nextval.ToString("000000");
                x.AddStorageBatchCode = $@"R{year}{suffix}";
                if (x.MaterArriDate == null)
                {
                    x.MaterArriDate = DateTime.Now;
                }
                x.AddStorageDate = DateTime.Now;
                x.RemainNum = x.Num;
            });
            
            var ls = (await _stockInRepository.baseRepository.InsertAsync(list));

            return ResponseOutput.Result(ls.Count > 0);
        }

        public async Task<IResponseOutput> UpdateAsync(StockInUpdateInput input)
        {
            if (!(input?.Id > 0))
            {
                return ResponseOutput.NotOk();
            }

            var entity = await _stockInRepository.GetAsync(input.Id);
            if (!(entity?.Id > 0))
            {
                return ResponseOutput.NotOk("库位不存在！");
            }


            //_xbcMaterrialRepository.GetResp().Where(x => x.Name.Equals(input.Name) && x.XbcWarehouseId.Equals(input.XbcWarehouseId)
            //&& x.IsDeleted == false && x.Id != input.Id)
            //    .Count(out var total);
            //if (total > 0)
            //{
            //    return ResponseOutput.NotOk("该仓库已存在相同库位！");
            //}

            _mapper.Map(input, entity);
            await _stockInRepository.UpdateAsync(entity);
            return ResponseOutput.Ok();
        }

        public async Task<IResponseOutput> SoftDeleteAsync(long id)
        {
            var result = await _stockInRepository.SoftDeleteAsync(id);
            return ResponseOutput.Result(result);
        }

        public async Task<IResponseOutput> BatchSoftDeleteAsync(long[] ids)
        {
            var result = await _stockInRepository.SoftDeleteAsync(ids);
            return ResponseOutput.Result(result);
        }

    }
}
